import type { FetchResponse, SearchParameters } from 'ofetch'
import { initTRPC, TRPCError } from '@trpc/server';
import { ofetch } from 'ofetch'

 interface AJKApiResponse<T> {
  status?: "ok" | string; // 状态，至少包含"ok"
  errcode?: number,
  code?: number; // 状态码
  message?: string; // 消息
  data?: T; // 数据主体
}
/**
 * 处理业务错误（HTTP状态码200，但业务code非200）
 */
const handleBusinessError = <T>(res: AJKApiResponse<T>) => {
  const message = res.message || `业务错误：${res.code}`

  throw createTrpcError(message)
}


const handleError = <T>(response: FetchResponse<AJKApiResponse<T>>) => {
  const err = (text: string) => {
    const msg = text ?? response?._data?.message
    // 请确保 message 已正确导入，以下代码示例使用 message 输出错误
    throw createTrpcError(`请求错误${msg}`)
  }
  if (!response._data) {
    err('请求超时，服务器无响应！')
    return
  }
  const handleMap: { [key: number]: () => void } = {
    404: () => err('服务器资源不存在'),
    500: () => err('服务器内部错误'),
    403: () => {
      err('登录状态已过期，请重新登录')
    },

    401: () => {
      err('登录状态已过期，请重新登录')
      // TODO 跳转实际登录页
    },
  }
  // 先获取处理函数
  const handler = handleMap[response.status];
  // 检查并调用
  if (handler) {
    handler();
  } else {
    err('未知错误！');
  }
}



// const config = useRuntimeConfig()
const createFetch = ofetch.create({
  // 请求拦截器
  onRequest({ request, options }) {

      

    // get方法传递数组形式参数
    // options.params = paramsSerializer(options.params)
    if (options.method === 'GET' && options.params) {
      options.query = { ...options.params }
    }

    // 添加baseURL,nuxt3环境变量要从useRuntimeConfig里面取

    // let url = 'https://vip.anjuke.com'
    // options.baseURL = config.public.ajkApiBase
    // options.baseURL = 'https://vip.anjuke.com'
    // options.credentials = 'include'

    // 当请求地址包含 /api/auth/login 或 /api/sysUser/register 时不检查 sysToken
    // console.log(requestUrl, acc58Token);
  },
  // 响应拦截
  onResponse({ response, options }) {
    
    // 校验响应格式是否符合AJKApiResponse
    const res = response._data as AJKApiResponse<unknown>
    // console.log(res);
    if (response.headers.get('content-type')?.includes('application/json')) {
      checkResp(options.baseURL as string, res)
    }
    // 业务状态码校验：成功则返回data，失败则抛错
    if (res.code === 200 || res.code === 0 || res.status === 'ok') {
      // console.log('解析成功');
      response._data = res.data
      return   // 直接返回data部分
    } else {
      // console.log('解析失败');
      handleBusinessError(res)
    }
    // return response._data
  },
  // 错误处理
  onResponseError({ response }) {
    handleError(response)
    return Promise.reject(response?._data ?? null)
  },
})
// 检查响应体
function checkResp(baseUrl: string, resp: AJKApiResponse<any>) {
  if (baseUrl === 'https://vip.anjuke.com') {
    if (resp === undefined || (resp.status || '') !== 'ok') {
      console.log(resp)
      throw createTrpcError(resp.message ?? '接口返回格式错误，缺少必要字段')
    }
  }
  if (baseUrl === 'https://cloud-passport.anjuke.com') {
  }
}

// 自动导出
export const httpUtils = {
  get: <T>(url: string, cookie: string, params?: any) => {
    let headers = {
      'cookie': cookie
    }
    const baseURL = 'https://vip.anjuke.com'
    return createFetch<T>(url, { method: 'get', params, headers, baseURL })
  },

  post: <T>(url: string, cookie: string, body?: any) => {
    let headers = {
      'cookie': cookie
    }
    const baseURL = 'https://vip.anjuke.com'
    return createFetch<T>(url, { method: 'post', body, headers, baseURL })
  },
  postForm: <T>(url: string, cookie: string, body?: any) => {
    let headers = {
      'cookie': cookie,
      'Content-Type': 'application/x-www-form-urlencoded'
    }
    const baseURL = 'https://vip.anjuke.com'
    return createFetch<T>(url, { method: 'post', body, headers, baseURL })
  },
  put: <T>(url: string, cookie: string, body?: any) => {
    let headers = {
      'cookie': cookie
    }
    const baseURL = 'https://vip.anjuke.com'
    return createFetch<T>(url, { method: 'put', body, headers, baseURL })
  },

  delete: <T>(url: string, cookie: string, body?: any) => {
    let headers = {
      'cookie': cookie
    }
    const baseURL = 'https://vip.anjuke.com'
    return createFetch<T>(url, { method: 'delete', body, headers, baseURL })
  },
}
